package com.offics.loan.infrastructure.persistence;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.offics.loan.domain.entity.LoanProduct;
import com.offics.loan.domain.repository.LoanProductRepository;
import com.offics.loan.infrastructure.persistence.mapper.LoanProductMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

/**
 * 贷款产品仓储实现类
 */
@Repository
@RequiredArgsConstructor
public class LoanProductRepositoryImpl extends ServiceImpl<LoanProductMapper, LoanProduct> implements LoanProductRepository {

    private final LoanProductMapper loanProductMapper;

    @Override
    public Optional<LoanProduct> findById(Long id) {
        return Optional.ofNullable(loanProductMapper.selectById(id));
    }

    @Override
    public Optional<LoanProduct> findByName(String name) {
        LambdaQueryWrapper<LoanProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LoanProduct::getName, name);
        return Optional.ofNullable(loanProductMapper.selectOne(wrapper));
    }

    @Override
    public List<LoanProduct> findAllEnabled() {
        LambdaQueryWrapper<LoanProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LoanProduct::getStatus, 1);
        wrapper.orderByAsc(LoanProduct::getId);
        return loanProductMapper.selectList(wrapper);
    }

    @Override
    public IPage<LoanProduct> findPage(IPage<LoanProduct> page, String name, Integer status) {
        LambdaQueryWrapper<LoanProduct> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(name)) {
            wrapper.like(LoanProduct::getName, name);
        }
        if (status != null) {
            wrapper.eq(LoanProduct::getStatus, status);
        }
        wrapper.orderByAsc(LoanProduct::getId);
        return loanProductMapper.selectPage(page, wrapper);
    }

    @Override
    public boolean save(LoanProduct loanProduct) {
        return loanProductMapper.insert(loanProduct) > 0;
    }

    @Override
    public LoanProduct saveAndReturn(LoanProduct loanProduct) {
        if (save(loanProduct)) {
            return loanProduct;
        }
        return null;
    }

    @Override
    public boolean update(LoanProduct loanProduct) {
        return loanProductMapper.updateById(loanProduct) > 0;
    }

    @Override
    public boolean deleteById(Long id) {
        return loanProductMapper.deleteById(id) > 0;
    }

    @Override
    public boolean existsByName(String name) {
        LambdaQueryWrapper<LoanProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LoanProduct::getName, name);
        return loanProductMapper.selectCount(wrapper) > 0;
    }
}
